package test.spring.boot.oauth.github.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ZCW
 * @createTime 2017/12/5
 * @lastUpdateTime 2017/12/5 ZCW
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    @Value("${OAuth.github.authorizationRequestUrl}")
    private String authorizationRequestUrl;

    @Value("${OAuth.github.tokenRequestUrl}")
    private String tokenRequestUrl;

    @Value("${OAuth.github.clientID}")
    private String clientId;

    @Value("${OAuth.github.clientSecret}")
    private String clientSecret;

    @Value("${OAuth.github.userRequestUrl}")
    private String userRequestUrl;

    /**
     * 跳转到登录页。显示连接指向 GitHub 登录页
     *
     * @author: ZCW
     * @createTime: 2017/12/11
     * @lastUpdateTime: 2017/12/11 ZCW
     * @param Model
     * @return:
     */
    @RequestMapping
    public String login(Model model) {
        model.addAttribute("authorizationRequestUrl", authorizationRequestUrl);
        return "login";
    }

    /**
     * 用户授权回调地址。
     * 通过code 获取 token
     * 通过 token 获取用户信息
     *
     * @author: ZCW
     * @createTime: 2017/12/11
     * @lastUpdateTime: 2017/12/11 ZCW
     * @param code
     * @param request
     * @return: java.util.Map
     */
    @RequestMapping("/github/authorizationCallBack")
    @ResponseBody
    public Map checkCode(String code, HttpServletRequest request) {

        Map<String ,String> params=new HashMap();
        params.put("client_id",clientId);
        params.put("client_secret",clientSecret);
        params.put("code",code);

        Map<String ,String> token = new RestTemplate()
                .postForObject(
                        tokenRequestUrl,
                        params,
                        Map.class
                );


        Map<String ,String> user = new RestTemplate()
                .getForObject(
                    String.format(userRequestUrl,token.get("access_token")),
                    Map.class
                );

        return user;
    }

    private Map sendHttpClientPOSTRequest(String path, Map<String, String> params) {


        return null;
    }

}
